/**
 * YearPlanningServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.jackysoft.entity.YearPlan;
import org.jackysoft.report.rows.YearPlanRowWatcher;
import org.jackysoft.service.AbstractStringIdServiceImpl;
import org.jackysoft.service.ProductService;
import org.jackysoft.service.YearPlanService;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service
@Transactional
public class YearPlanServiceImpl extends AbstractStringIdServiceImpl<YearPlan>
		implements YearPlanService {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7826767080981896319L;	
    private ProductService productService;
    private YearPlanRowWatcher  yearRowWatcher;
	public YearPlanServiceImpl() {
		this.type = YearPlan.class;
	}


	@Resource
	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	@Override
	public void remove(YearPlan t) throws DataAccessException {
		t = get(t.getId());
		super.remove(t);
	}

	@Override
	public Collection<YearPlan> getYear(int year)
			throws DataAccessException {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void importData(int year, File file) throws DataAccessException {
		final Collection<YearPlan> plans = Lists.newArrayList();
		final List<String> errors = Lists.newArrayList();
		try {
			HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(file));
			int sheetCount = workbook.getNumberOfSheets();
			yearRowWatcher.starup(productService, plans, errors, year);
			for (int i = 0; i < sheetCount; i++) {

				HSSFSheet sheet = workbook.getSheetAt(i);
				Iterator<Row> rows = sheet.rowIterator();
				while(rows.hasNext()){
					Row row = rows.next();
					yearRowWatcher.accept(row);
				}			
			}
			
			
			//create(plans);
			for(YearPlan plan : plans)
				log.info(plan);
			
			for(String str:errors)
				log.info(str);
		}catch (IOException e) {
		    log.error(e);
			e.printStackTrace();
		}
		
	}




	@Resource
	public void setYearRowWatcher(YearPlanRowWatcher yearRowWatcher) {
		this.yearRowWatcher = yearRowWatcher;
	}
	
	

}